package com.hjh.gameforum.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hjh.gameforum.dto.ReplyDto;
import com.hjh.gameforum.dto.ReplyQueryParem;
import com.hjh.gameforum.entity.Reply;
import com.hjh.gameforum.mapper.ReplyFavoritesMapper;
import com.hjh.gameforum.mapper.ReplyMapper;
import com.hjh.gameforum.result.PageResult;
import com.hjh.gameforum.service.ReplyService;
import com.hjh.gameforum.utils.CurrentHolder;
import com.hjh.gameforum.vo.ReplyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private ReplyFavoritesMapper replyFavoritesMapper;

    @Override
    public void createReply(ReplyDto replyDto) {
        Long userId = CurrentHolder.getCurrentId();
        Reply reply = Reply.builder()
                .content(replyDto.getContent())
                .createdAt(LocalDateTime.now())
                .topicId(replyDto.getTopicId())
                .userId(userId)
                .build();
        replyMapper.createReply(reply);
    }

    @Override
    public PageResult<ReplyVo> getReplyList(ReplyQueryParem replyQueryParem) {
        PageHelper.startPage(replyQueryParem.getPage(), replyQueryParem.getPageSize());
        List<ReplyVo> replies = replyMapper.getReplyList(replyQueryParem.getTopicId());
        Page<ReplyVo> page = (Page<ReplyVo>) replies;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void likeReply(Integer id) {
        replyMapper.likeReply(id);
        replyFavoritesMapper.createFavorites(CurrentHolder.getCurrentId(), id);
    }

    @Override
    @Transactional
    public void unlikeReply(Integer id) {
        replyMapper.unlikeReply(id);
        replyFavoritesMapper.deleteFavorites(CurrentHolder.getCurrentId(), id);

    }

    @Override
    public boolean getLikeStatus(Integer id) {
        return replyFavoritesMapper.getFavorites(CurrentHolder.getCurrentId(), id);
    }

    @Override
    public Long getTotalReplys() {
        return replyMapper.getTotalReplys();
    }
}
